from fastapi import HTTPException
from pydantic import BaseModel, Field
from ..dependencies import success, me, router, depens
from ..models.user import Address, Favorite, Focus, History
from ..models.base import Item, Shop, User
from typing import Dict
from ..dependencies import app
from datetime import date, datetime

### 个人中心
@router.get('/me', tags=['user'], dependencies=depens(False))
async def index():
    if me() is None:
        items = [row for row in Item.select().paginate(1, 10).dicts()]
        return success({'items': items})
    else:
        return success(me())
### 更新
@router.put('/me', tags=['user'], dependencies=depens())
async def update(params: Dict):
    User.update(params).where(User.id == me('id')).execute()
    return success()

### 用户详情
@router.get("/user/{id}", tags=["user"], dependencies=depens())
async def read(id: int):
    model = User.get(User.id == id)
    if model == None:
        raise HTTPException(status_code=404, detail="User not found")
    return success(model.__data__)

#################
##### 收货地址 ###
#################

class AddressForm(BaseModel):
    consignee: str = Field(title="收货人", default='', max_length=20)
    mobile: str = Field(title="手机号", default='', max_length=11)
    dist_id: int = Field(title="地区", default=0)
    detail: str = Field(title="详细", default='', max_length=50)

### 列表
@router.get('/address', tags=["user"], dependencies=depens())
async def index(page: int = 1, size: int = 10):
    list = [row for row in Address.select().where(Address.user_id==me('id')).order_by(Address.id.desc()).paginate(page, size).dicts()]
    return success({
        'list': list,
        'total': Address.select().where(Address.user_id == me('id')).count()
    })
### 读取
@router.get('/address/{id}', tags=["user"], dependencies=depens())
async def read(id: int):
    model = Address.get(Address.id == id, Address.user_id==me('id'))
    if model == None:
        raise HTTPException(status_code=404, detail="Address not found")
    return success({'form': model.__data__})
### 创建
@router.post('/address', tags=["user"], dependencies=depens())
async def save(data: AddressForm):
    model = Address.create(user_id=me('id'), **data.__dict__)
    return success(model)
### 更新
@router.put('/address/{id}', tags=["user"], dependencies=depens())
async def update(id: int, data: AddressForm):
    Address.update(data.__dict__).where(Address.id==id, Address.user_id==me('id')).execute()
    return success()
### 删除
@router.delete('/address/{id}', tags=["user"], dependencies=depens())
async def delete(id: int):
    Address.delete().where(Address.id==id, Address.user_id==me('id')).execute()
    return success()

#################
##### 收藏 ######
#################
### 列表
@router.get('/favorite', tags=['user'], dependencies=depens())
async def index(page: int = 1, size: int = 10):
    list = [{**row, 'create_at': datetime.fromtimestamp(row['create_at'])} for row in Favorite.select(Favorite.id, Favorite.item_id, Favorite.create_at, Item.price, Item.name, Item.thumb, Item.shop_id, Shop.name.alias('shop_name')).join(Item).join(Shop).where(Favorite.user_id==me('id')).order_by(Favorite.id.desc()).paginate(page, size).dicts()]
    return success({
        'list': list,
        'total': Favorite.select().where(Favorite.user_id==me('id')).count()
    })
### 更新
@router.put('/favorite/{id}', tags=['user'], dependencies=depens())
async def update(id: int):
    if Favorite.select().where(Favorite.user_id==me('id'), Favorite.item_id==id).exists():
        Favorite.delete().where(Favorite.user_id==me('id'), Favorite.item_id==id).execute()
    else:
        item = Item.select(Item.name, Item.price, Item.thumb).where(Item.id==id).get()
        Favorite.create(user_id=me('id'), item_id=id, **item.__data__)
    return success()
### 删除
@router.delete('/favorite/{id}', tags=['user'])
async def delete(id: int):
    Favorite.delete().where(Favorite.id == id).execute()
    return success()

#################
##### 关注 ######
#################

### 列表
@router.get('/focus', tags=['user'], dependencies=depens())
async def index(page: int = 1, size: int = 10):
    list = [{**row, 'create_at': datetime.fromtimestamp(row['create_at'])} for row in Focus.select().where(Focus.user_id == me('id')).order_by(Focus.id.desc()).paginate(page, size).dicts()]
    return success({
        'list': list,
        'total': Focus.select().where(Focus.user_id == me('id')).count()
    })
### 更新
@router.put('/focus/{id}', tags=['user'], dependencies=depens())
async def update(id: int):
    if Focus.select().where(Focus.user_id==me('id'), Focus.item_id==id).exists():
        Focus.delete().where(user_id=me('id'), item_id=id).execute()
    else:
        shop = Shop.select(Item.name, Item.thumb).where(Item.id==id).get()
        Focus.create(user_id=me('id'), item_id=id, **shop.__data__)
    return success()
### 删除
@router.delete('/focus/{id}', dependencies=depens())
async def delete(id: int):
    Focus.delete().where(Focus.id==id).execute()
    return success()

#################
##### 浏览足迹 ######
#################

### 列表
@router.get('/history', tags=['user'], dependencies=depens())
async def index(page: int = 1, size: int = 10):
    list = [{**row, 'date': date.fromtimestamp(row['create_at'])} for row in History.select(History.id, History.item_id, History.name, History.price, History.thumb, History.create_at).where(History.user_id == me('id')).order_by(History.create_at.desc()).paginate(page, size).dicts()]
    return success({
        'list': list,
        'total': History.select().where(History.user_id == me('id')).count()
    })
### 更新
@router.put('/history/{id}', tags=['user'], dependencies=depens())
async def update(id: int):
    if History.select().where(History.user_id==me('id'), History.item_id==id).exists():
        History.update({}).where(user_id=me('id'), item_id=id).execute()
    else:
        History.create(user_id=me('id'), item_id=id)
    return success()
### 删除
@router.delete('/history/{id}', tags=['user'], dependencies=depens())
async def delete(id: int):
    History.delete().where(History.id == id).execute()
    return success()


@router.post("/logout", tags=['user'], dependencies=depens())
async def logout():
    app.state.user = None
    return success()
